package com.augurit.smartform.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;

import com.augurit.common.entity.SysMetaTable;
import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.PageUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.smartform.constant.PageConstant;
import com.augurit.smartform.converter.PageConverter;
import com.augurit.smartform.dao.SmFunctionDao;
import com.augurit.smartform.dao.SmPageDao;
import com.augurit.smartform.display.PageElement;
import com.augurit.smartform.display.PageResolve;
import com.augurit.smartform.display.TagElement;
import com.augurit.smartform.entity.SmPage;
import com.augurit.smartform.service.ISmartFormService;
import com.augurit.smartform.service.IPageMgmtService;
import com.augurit.smartform.web.parser.form.SmPageForm;
import com.augurit.wf.bi.service.IWfActElemPrivDefService;
import com.augurit.wf.bi.service.IWfBusTemplateService;
import com.augurit.wf.bi.service.IWfPageElementService;
import com.augurit.wf.bi.web.form.WfBusTemplateForm;
import com.augurit.wf.bi.web.form.WfPageElementForm;
import com.augurit.wf.common.dao.WfTemplateElementRefDao;
import com.augurit.wf.common.entity.WfTemplateElementRef;

@Service
@Transactional
public class PageMgmtService implements IPageMgmtService {
	@Autowired
	private SmPageDao pageDao;
	@Autowired
	private SmFunctionDao smFunctionDao;
	@Autowired
	private ISmartFormService smartFormService;
	@Autowired
	private PageResolve pageResolve;
	@Autowired
	private IWfPageElementService wfPageElementService;
	@Autowired
	private IWfActElemPrivDefService wfActElemPrivDefService;
	@Autowired
	private WfTemplateElementRefDao wfTemplateElementRefDao;
	@Autowired
	private IWfBusTemplateService wfBusTemplateService;
	
	/**
	 * 根据主键获取Form对象
	 */
	@Transactional(readOnly = true)
	public SmPageForm get(Long id){
		SmPage smPage=pageDao.get(id);
		SmPageForm pageForm=PageConverter.convertToPageForm(smPage);
		if(StringUtils.isNotBlank(smPage.getName())){
			SysMetaTable smForm=smartFormService.getLastedSmFormByName(smPage.getName().toUpperCase());
			if(smForm!=null){
				pageForm.setLastedTableName(smForm.getTableName());
				pageForm.setLastedParentTableName(smForm.getParentTableName());
			}
		}
		return pageForm;
	}
	
	/**
	 * 查询所有SMPAGE记录
	 * @param page
	 * @param form
	 * @return
	 */
	@Transactional(readOnly = true)
	public Page<SmPageForm> findPage(Page<SmPageForm> page,SmPageForm form){
		// 建立新的分页对象
		Page<SmPage> pg = PageUtils.newPageInstance(page);
		
		StringBuilder hql = new StringBuilder("from SmPage sp where 1=1");
		List<Object> values = new ArrayList<Object>();
		
		// 查询条件
		if(form != null){
			if(StringUtils.isNotBlank(form.getName())){
				hql.append(" and sp.name like ?");
				values.add("%" + form.getName().trim().toUpperCase() + "%");
			}
			if(StringUtils.isNotBlank(form.getPageCode())){
				hql.append(" and sp.pageCode like ?");
				values.add("%" + form.getPageCode().trim() + "%");
			}
			if(StringUtils.isNotBlank(form.getCnName())){
				hql.append(" and sp.cnName like ?");
				values.add("%" + form.getCnName().trim() + "%");
			}
			if(form.getPageDirId()!=null){
				hql.append(" and sp.pageDirId = ?");
				values.add(form.getPageDirId());
			}
			if(form.getId()!=null){
				hql.append(" and sp.id = ?");
				values.add(form.getId());
			}
		}
		
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "sp"));
		
		// 执行分页查询操作
		pageDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<SmPageForm> smPageForms=PageConverter.convertToFormList(pg.getResult());
		PageUtils.copy(pg, smPageForms, page);
		
		return page;
	}
	
	/**
	 * 查询所有SMPAGE记录
	 * @param page
	 * @param form
	 * @return
	 * cuigeqiang
	 */
	@Transactional(readOnly = true)
	public Page<SmPageForm> findPageWithTableInfo(Page<SmPageForm> page,SmPageForm form){
		Page<SmPageForm> smartPages=this.findPage(page, form);
		this.addTemplateInfo(smartPages);
		this.addTableInfoToPageForm(smartPages);
//		List<SysMetaTable> lastedSmartForms=smartFormService.getAllLastedSmartForms();
//		this.addTableInfoToPageForm(smartPages, lastedSmartForms);
		return smartPages;
	}
	
	/**
	 * 取得数据库相关联的页面
	 * @param id
	 * @return
	 * cuigeqiang
	 */
	public SmPageForm getDbRelationPage(Long id){
		SmPageForm returnPage=null;
		SmPage smPage=pageDao.get(id);
		if(smPage!=null){
			if(StringUtils.isNotBlank(smPage.getName())){
				SysMetaTable sysMetaTable=smartFormService.getLastedSmFormByName(smPage.getName().toUpperCase());
				if(sysMetaTable!=null){
					if(smPage.getPageId()!=null&&smPage.getPageId().equals(sysMetaTable.getPageId())){
						returnPage=PageConverter.convertToPageForm(smPage);
					}
				}
			}
		}
		return returnPage;
	}
	
	/**
	 * 通过PAGEID和系统绝对路径删除相关的智能表单
	 * @param pageId
	 */
	public void deleteSmartForm(Long pageId,String absolutePath){
		SmPage smPage=pageDao.get(pageId);
		SysMetaTable sysMetaTable=this.getDbRelationTable(smPage);
		
		if(smPage!=null&&smPage.getTemplateId()!=null){
			this.deleteWfRelation(smPage, sysMetaTable);
		}
		
		this.deleteFtlJspFile(smPage, absolutePath);
		
		if(sysMetaTable!=null&&sysMetaTable.getFormName()!=null){
			smartFormService.deleteAllSmFormByName(sysMetaTable.getFormName().toUpperCase());
		}
		
		smFunctionDao.deleteByPageId(pageId);
		
		pageDao.delete(pageId);
	}
	
	/**
	 * 得到没有目录的页面
	 * @return
	 */
	public List<SmPageForm> getNoDirSmPages(){
		List<SmPage> smPageList= pageDao.getNoDirSmPages();
		return PageConverter.convertToFormList(smPageList);
	}
	
	/**
	 * 通过dirId查询SMPAGE列表
	 * @param pageId
	 * @return
	 * cuigeqiang
	 */
	public List<SmPageForm> getSmPageByDirId(Long dirId){
		List<SmPage> smPageList= pageDao.getSmPageByDirId(dirId);
		return PageConverter.convertToFormList(smPageList);
	}
	
	/**
	 * 更新目录ID
	 * @param smPageId
	 * @param dirId
	 * cuigeqiang
	 */
	public void updateDirId(Long smPageId,Long dirId){
		pageDao.updateDirId(smPageId, dirId);
	}
	
	/**
	 * 向页面FORM中加入数据表信息
	 * @param smartPages
	 * @param lastedSmartForms
	 * cuigeqiang
	 */
	private void addTableInfoToPageForm(Page<SmPageForm> smartPages,List<SysMetaTable> lastedSmartForms){
		if(smartPages.getResult()!=null&&smartPages.getResult().size()>0){
			for(SmPageForm smPageForm : smartPages.getResult()){
				if(lastedSmartForms!=null&&lastedSmartForms.size()>0){
					for(SysMetaTable table : lastedSmartForms){
						String formName=smPageForm.getName();
						if(formName!=null&&formName.equalsIgnoreCase(table.getFormName())){
							smPageForm.setLastedTableName(table.getTableName());
							smPageForm.setLastedParentTableName(table.getParentTableName());
							break;
						}
					}
				}
			}
		}
	}
	
	/**
	 * 向页面FORM中加入数据表信息
	 * @param smartPages
	 * @param lastedSmartForms
	 * cuigeqiang
	 */
	private void addTableInfoToPageForm(Page<SmPageForm> smartPages){
		if(smartPages.getResult()!=null&&smartPages.getResult().size()>0){
			for(SmPageForm smPageForm : smartPages.getResult()){
				SysMetaTable sysMetaTable=smartFormService.getLastedSmFormByName(smPageForm.getName());
				if(sysMetaTable!=null){
					smPageForm.setLastedTableName(sysMetaTable.getTableName());
					smPageForm.setLastedParentTableName(sysMetaTable.getParentTableName());
				}
			}
		}	
	}
	
	/**
	 * 流程表单加入模板信息
	 * @param smartPages
	 * cuigeqiang
	 */
	private void addTemplateInfo(Page<SmPageForm> smartPages){
		if(smartPages.getResult()!=null&&smartPages.getResult().size()>0){
			for(SmPageForm smPageForm : smartPages.getResult()){
				Long templateId=smPageForm.getTemplateId();
				if(templateId!=null){
//					WfBusTemplateForm templateForm=wfBusTemplateService.get(templateId);
					WfBusTemplateForm templateForm=wfBusTemplateService.findById(templateId);
					if(templateForm!=null){
						smPageForm.setTemplateName(templateForm.getTemplateName());
					}
				}
			}
		}	
	}
	
	/**
	 * 删除FTL和JSP文件
	 * @param pageId
	 * @param absolutePath
	 * cuigeqiang
	 */
	private void deleteFtlJspFile(SmPage smPage,String absolutePath){
		String fullFtlPath=absolutePath+smPage.getSourcePath();
		String fullJspPath=absolutePath+smPage.getJspPath();
		File ftlFile=new File(fullFtlPath);
		ftlFile.delete();
		File jspFile=new File(fullJspPath);
		jspFile.delete();
	}
	
	/**
	 * 取得数据库相关联的页面
	 * @param smPage
	 * @return
	 * cuigeqiang
	 */
	private SysMetaTable getDbRelationTable(SmPage smPage){
		SysMetaTable returnTable=null;
		if(smPage!=null){
			if(StringUtils.isNotBlank(smPage.getName())){
				SysMetaTable sysMetaTable=smartFormService.getLastedSmFormByName(smPage.getName().toUpperCase());
				if(sysMetaTable!=null){
					if(smPage.getPageId()!=null&&smPage.getPageId().equals(sysMetaTable.getPageId())){
						returnTable=sysMetaTable;
					}
				}
			}
		}
		return returnTable;
	}
	
	/**
	 * 删除工作流相关的数据
	 * @param smPage
	 * @param sysMetaTable
	 * cuigeqiang
	 */
	private void deleteWfRelation(SmPage smPage,SysMetaTable sysMetaTable){
		this.deleteElementAndRef(smPage);
		if(sysMetaTable!=null){
			this.updateTemplate(smPage, sysMetaTable);
		}
	}
	
	/**
	 * 删除页面元素以及引用
	 * @param smPage
	 * cuigeqiang
	 */
	private void deleteElementAndRef(SmPage smPage){
		Long templateId=smPage.getTemplateId();
		if(templateId!=null){
			PageElement page=pageResolve.paser(smPage.getSourceXml());
			String elementCode=page.getPageCode()+PageConstant.FORM_SUFFIX;
			WfPageElementForm form = wfPageElementService.getByElementCode(elementCode);
			Iterator<TagElement> tags=page.getElements().values().iterator();
			while(tags.hasNext()){
				TagElement tag=tags.next();
				WfPageElementForm tagElement=wfPageElementService.getByElementCode(tag.getId());
				
				if(tagElement!=null){
					//删除页面元素与模板的关联
					WfTemplateElementRef entity = wfTemplateElementRefDao.get(templateId, tagElement.getId());
					if(entity != null){
						wfTemplateElementRefDao.delete(entity);
					}
					wfActElemPrivDefService.deleteByElemPrivInTemplate(templateId, tagElement.getId());
					//删除非公有页面元素
					if(tagElement.getIsPublic() == null || tagElement.getIsPublic().equals(WfPageElementForm.NOT_PUBLIC)){
						wfPageElementService.delete(tagElement.getId());
					}
				}
			}
			if(form!=null){
				WfTemplateElementRef formEntity = wfTemplateElementRefDao.get(templateId, form.getId());
				if(formEntity != null){
					wfTemplateElementRefDao.delete(formEntity);
				}
				if(form.getIsPublic() == null || form.getIsPublic().equals(WfPageElementForm.NOT_PUBLIC)){
					wfPageElementService.delete(form.getId());
				}
			}
		}
	}
	
	/**
	 * 更新模板
	 * @param smPage
	 * @param sysMetaTable
	 * cuigeqiang
	 */
	private void updateTemplate(SmPage smPage,SysMetaTable sysMetaTable){
		Long templateId=smPage.getTemplateId();
		if(templateId!=null){
			WfBusTemplateForm templateForm=wfBusTemplateService.findById(templateId);
			if(templateForm!=null){
				String oldMasterEntity=templateForm.getMasterEntity();
				String oldSlaveEntities=templateForm.getSlaveEntities();
				if(oldMasterEntity!=null&&oldMasterEntity.equals(sysMetaTable.getTableName())){
					templateForm.setMasterEntity("");
				}
				
				List<String> slaveEntityList=new ArrayList<String>();
				String[] oldSlaveEntitiesArray=new String[]{};
				if(StringUtils.isNotBlank(oldSlaveEntities)){
					oldSlaveEntitiesArray=oldSlaveEntities.split(PageConstant.COMMA_SEPERATOR);
				}
				for(String oldSlaveEntity : oldSlaveEntitiesArray){
					slaveEntityList.add(oldSlaveEntity);
				}
				for(String slaveEntity : slaveEntityList){
					if(slaveEntity.equals(sysMetaTable.getTableName())){
						slaveEntityList.remove(slaveEntity);
						break;
					}
				}
				templateForm.setSlaveEntities(StringUtils.convertStringListToString(slaveEntityList, PageConstant.COMMA_SEPERATOR));
				wfBusTemplateService.saveBySmartForm(templateForm);
			}
		}
	}
}
